package com.yu.xcx.controller;


import com.yu.xcx.dto.Result;
import com.yu.xcx.entity.User;
import com.yu.xcx.service.IUserInfoService;
import com.yu.xcx.service.IUserService;
import org.springframework.web.bind.annotation.*;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;

import javax.annotation.Resource;


@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @PostMapping("/login")
    public Result saveUser(String openId, String sekey, String nickName){
        User user2 = userService.login(openId,sekey,nickName);
        if (user2 == null){
            return Result.fail("存储数据失败");
        }
        String token = getToken(user2);
        return Result.ok(token);
    }

    @GetMapping("/selectByOpenId")
    public Result selectOpenId(String openId){
        return userService.selectOpenId(openId);
    }

    public String getToken(User user) {
        String token="";
        token= JWT.create()
                .withKeyId(user.getId().toString())
                .withIssuer("www.ikertimes.com")
                .withIssuedAt(new Date())
                .withJWTId("jwt.ikertimes.com")
                .withClaim("session_key", user.getSekey())
                .withAudience(user.getId().toString())
                .sign(Algorithm.HMAC256(user.getOpenId()));
        return token;
    }

    @GetMapping("/selectById")
    public Result selectById(Integer id){
        return userService.selectById(id);
    }
}
